package rpg.state
{
	import flash.utils.Dictionary;
	
	import rpg.Utils.Val;
	import rpg.avatar.AvatarComponent;
	import rpg.core.FrameComponent;
	import rpg.role.Hero;

	/**
	 * 状态机
	 * @author hyy
	 *
	 */
	public class StateComponent extends FrameComponent
	{
		private var hero : Hero;
		private var statesClass : Array;
		private var stateDictionary : Dictionary = new Dictionary();
		private var currState : StateBase;
		private var avatarComponent : AvatarComponent;

		public function StateComponent(type : *)
		{
			super(type);
		}

		override public function notifyAdded() : void
		{
			hero = owner as Hero;
			avatarComponent = hero.getComponent(AvatarComponent);
		}

		override public function update(delay : uint) : void
		{
			if(!currState)
				return;
			currState.update(delay);
		}

		public function changeState(id : int) : Boolean
		{
			if(!stateDictionary[id])
			{
				id = Val.STAND;
			}
			if(currState)
				currState.clear();
			currState = stateDictionary[id];
			return true;
		}

		/**
		 * 走到目标的位置需要实行的函数
		 * @param fun
		 *
		 */
		public function walkFinishFun(targetMapX : int , targetMapY : int , returnFun : Function) : void
		{
			hero.targetMapX = targetMapX;
			hero.targetMapY = targetMapY;
			changeState(Val.WALK);
			stateDictionary[Val.WALK].returnFun = returnFun;
		}

		public function setRoleAnimation(statesClass : Array) : void
		{
			this.statesClass = statesClass;
			for each(var stateClass : Class in statesClass)
			{
				var state : StateBase = new stateClass(hero , this);
				stateDictionary[state.stateID] = state;
			}
		}

		public function destory() : void
		{
			stateDictionary = null;
			currState = null;
		}

	}
}